/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bsc.war.form;

import bsc.ejb.entity.Note;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.PersonScoreCard;
import bsc.ejb.entity.PersonScoreDomain;
import bsc.war.ajax.DeleteNote;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author luisZavaleta
 */
public class DeletePerson extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            Person person = delegate.findPerson(Long.valueOf(request.getParameter("id")));

            List<PersonScoreDomain> personScoreDomains = delegate.findPersonScoreDomain(person);
            List<PersonScoreCard> personScoreCard = delegate.findPersonScoreCard(person);

            boolean deleted = false;

            if(personScoreCard.isEmpty()){
                for (PersonScoreDomain personScoreDomain : personScoreDomains) delegate.deletePersonScoreDomain(personScoreDomain);
                List<Note> notes = delegate.findNote(person);
                for (Note note : notes) DeleteNote.processRequestInternal(request, response, delegate, note);

                delegate.deletePerson(person);
                deleted = true;
            }
            request.setAttribute("deleted", deleted);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new ModelAndView("deletePerson");

    }

}
